Find LCM Using C++

03-11-17 Course- CPP

LCM of two integers a and b is the smallest positive integer that is divisible by both a and b.

1. Source Code to Find LCM


#include <iostream>
using namespace std;

int main() {
    int n1, n2, max;
    cout << "Enter two numbers: ";
    cin >> n1 >> n2;
    
    max = (n1 > n2) ? n1 : n2; // maximum value between n1 and n2 is stored in max

    do {
        if (max%n1 == 0 && max%n2 == 0) {
            cout << "LCM = " << max;
            break;
        }
        else
            ++max;
    }
    while (true);
    
    return 0;
}

Output


Enter two numbers: 12
18
LCM = 36

In above program, user is asked to integer two integers n1 and n2 and largest of those two numbers is stored in max. It is checked whether max is divisible by n1 and n2, if it's divisible by both numbers, max(which contains LCM) is printed and loop is terminated. If not, value of max is incremented by 1 and same process goes on until maxis divisible by both n1 and n2.

Source Code to find LCM using HCF

The LCM of two numbers is give by:


LCM = (n1*n2)/HCF

#include <iostream>
using namespace std;

int main() {
    int n1, n2, temp1, temp2, lcm;
    cout << "Enter two numbers: ";
    cin >> n1 >> n2;

    temp1 = n1;
    temp2 = n2;
    
    while(temp1 != temp2) {
        if(temp1 > temp2)
            temp1 -= temp2;
        else
            temp2 -= temp1;
    }

    lcm = (n1 * n2) / temp1;

    cout << "LCM = " << lcm;
    return 0;
}